package com.mooer.app;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.mooer.MooerApplication;
import com.mooer.R;
import com.mooer.bean.SearchLocation;
import com.mooer.bean.Shop;
import com.mooer.config.Const;
import com.mooer.exception.SVException;
import com.mooer.http.HttpUtils;
import com.mooer.utils.ui.ProgressLinearLayout;

/**
 * @author pengfei.xu
 * @version 创建时间：2011-6-11 下午05:18:05 类说明
 */
public class BusinessList extends Activity implements OnClickListener,
		OnItemClickListener {

	private final String TAG = "BusinessList";

	private MooerApplication mooerApp;

	private TextView title, num, rigion, type, concern;

	private ImageView rigionButton, typeButton, concernButton;

	private ListView listView;

	private ProgressLinearLayout footer;

	private BusinessAdapter adapter;

	private List<Shop> shopList = new ArrayList<Shop>();

	private int categoryId = 0;

	private long taskId;

	SearchLocation location;

	private CharSequence[] items1 = new CharSequence[] { "附近500米", "附近1000米",
			"附近2000米" };

	private CharSequence[] items2 = new CharSequence[] { "距离", "评分", "关注度",
			"有无优惠券", "信息丰富度" };

	private CharSequence[] items3 = new CharSequence[Const.types.size() - 1];

	private int rigionItem, typeItem, concernItem = 2;

	private int listType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.business_list);
		mooerApp = (MooerApplication) getApplication();
		Intent intent = getIntent();
		categoryId = intent.getIntExtra("categoryId", 67);
		rigion = (TextView) findViewById(R.id.rigion);
		type = (TextView) findViewById(R.id.type);
		concern = (TextView) findViewById(R.id.concern);
		title = (TextView) findViewById(R.id.title);
		num = (TextView) findViewById(R.id.business_num);
		rigionButton = (ImageView) findViewById(R.id.rigion_btn);
		typeButton = (ImageView) findViewById(R.id.type_btn);
		concernButton = (ImageView) findViewById(R.id.concern_btn);
		listView = (ListView) findViewById(R.id.listview);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);

		adapter = new BusinessAdapter(this, shopList);
		listView.setAdapter(adapter);

		title.setText(intent.getStringExtra("type1") + "-"
				+ intent.getStringExtra("type2"));
		type.setText(intent.getStringExtra("type2"));
		num.setText(getString(R.string.business_num, 0));

		rigionButton.setOnClickListener(this);
		typeButton.setOnClickListener(this);
		concernButton.setOnClickListener(this);
		listView.setOnItemClickListener(this);
		footer.setOnClickListener(this);

		location = new SearchLocation();
		// location.setLatitude(mooerApp.getLatitude());
		// location.setLongitude(mooerApp.getLongitude());
		location.setSearch(intent.getStringExtra("content") == null ? ""
				: intent.getStringExtra("content"));
		if ("搜索".equals(intent.getStringExtra("type1"))) {
			listType = 1;
		} else {
			location.setLatitude(32.05724);
			location.setLongitude(118.740275);
			location.setRadius(500);
			location.setRegion(3);
			location.setOrderBy("concern_num");
			location.setCategory(categoryId);
			if ("搜索".equals(intent.getStringExtra("type2"))) {
				listType = 1;
			} else {
				listType = 0;
			}
		}
		new BusinessListTask(listType).execute(location);
	}

	@Override
	public void onClick(View v) {
		if (v == rigionButton) {
			// showSortWindow("rigion");
			showAlertDialog("距离", rigionItem);
		} else if (v == typeButton) {
			showAlertDialog("分类", typeItem);
		} else if (v == concernButton) {
			showAlertDialog("排序", concernItem);
		} else if (v == footer.reload) {
			footer.setVisibility(View.VISIBLE, View.VISIBLE, View.GONE,
					View.GONE);
			new BusinessListTask(listType).execute(location);
		}

	}

	public class BusinessListTask extends
			AsyncTask<SearchLocation, Integer, List<Shop>> {

		private int type; // 0 非搜索 1 搜索

		private boolean isException;

		public BusinessListTask(int type) {
			this.type = type;
		}

		@Override
		protected List<Shop> doInBackground(SearchLocation... location) {
			List<Shop> list = null;
			try {
				if (type == 0) {
					list = HttpUtils.fetchNearShopList(location[0], 0, 100);
				} else if (type == 1) {
					list = HttpUtils
							.fetchShopListByCategory(location[0], 0, 10);
				}
				for (Shop shop : list) {
					shop.setIcon(mooerApp.getShopListDefaultIcon());
				}
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<Shop> result) {
			super.onPostExecute(result);
			if (isException) {
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					listView.removeFooterView(footer);
					shopList.addAll(result);
					adapter.notifyDataSetChanged();
					num.setText(getString(R.string.business_num,
							shopList.size()));
					new BitmapTask().execute("");
				} else {
					footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
							View.GONE);
					footer.setText(null, "暂无符合条件的商家列表");
				}
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		Shop shop = shopList.get(position).copy();
		Intent intent = new Intent(BusinessList.this, Business.class);
		intent.putExtra("businessInfo", shop);
		startActivity(intent);
	}

	// private void showSortWindow(final String type) {
	// View popup = (LinearLayout) LayoutInflater.from(this).inflate(
	// R.layout.popupwindow_sort, null);
	// final PopupWindow pw = new PopupWindow(popup, LayoutParams.FILL_PARENT,
	// LayoutParams.WRAP_CONTENT);
	//
	// pw.setFocusable(true);
	// popup.setFocusableInTouchMode(true);
	// popup.setOnKeyListener(new OnKeyListener() {
	//
	// @Override
	// public boolean onKey(View v, int keyCode, KeyEvent event) {
	// System.out.println(keyCode + " " + KeyEvent.KEYCODE_BACK);
	// if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	// pw.dismiss();
	// return true;
	// }
	// return false;
	// }
	// });
	// pw.showAtLocation(findViewById(R.id.main), Gravity.CENTER_VERTICAL
	// | Gravity.CENTER, 50, 0);
	// ListView _listView = (ListView) popup.findViewById(R.id.listview);
	// final List<Map<String, Object>> _list = new ArrayList<Map<String,
	// Object>>();
	// final SimpleAdapter _adapter = new SimpleAdapter(BusinessList.this,
	// _list, R.layout.popupwindow_sort_item, new String[] { "select",
	// "content" }, new int[] { R.id.select, R.id.content });
	// _adapter.setViewBinder(new BitmapViewBinder());
	// _listView.setAdapter(_adapter);
	// final List<String> contents = getList(type);
	// for (int i = 0; i < contents.size(); i++) {
	// Map<String, Object> _map = new HashMap<String, Object>();
	// if ("rigion".equals(type) && rigionPosition == i) {
	// _map.put("select",
	// getResources().getDrawable(R.drawable.b_list_align_in));
	// } else {
	// _map.put("select",
	// getResources().getDrawable(R.drawable.b_list_align_on));
	// }
	// _map.put("content", contents.get(i));
	// _list.add(_map);
	// }
	// _listView.setOnItemClickListener(new OnItemClickListener() {
	//
	// @Override
	// public void onItemClick(AdapterView<?> arg0, View arg1,
	// int position, long arg3) {
	// _list.get(position).put("select",
	// getResources().getDrawable(R.drawable.b_list_align_in));
	// _adapter.notifyDataSetChanged();
	// if ("rigion".equals(type)) {
	// if (position != rigionPosition) {
	// System.out.println("selected:" + position);
	// rigionPosition = position;
	// rigion.setText(contents.get(position));
	// shopList.clear();
	// adapter.notifyDataSetChanged();
	// listView.addFooterView(footer);
	// if (position == 0) {
	// location.setRadius(500);
	// } else if (position == 1) {
	// location.setRadius(1000);
	// } else if (position == 1) {
	// location.setRadius(2000);
	// }
	// new BusinessListTask().execute(location);
	// }
	// }
	// pw.dismiss();
	// }
	// });
	//
	// }

	private List<String> getList(String type) {
		List<String> list = new ArrayList<String>();
		if ("rigion".equals(type)) {
			list.add("附近500米");
			list.add("附近1000米");
			list.add("附近2000米");
		}
		return list;
	}

	private void showAlertDialog(final String title, int selected) {
		CharSequence[] items = items1;
		if ("距离".equals(title)) {
			items = items1;
		} else if ("排序".equals(title)) {
			items = items2;
		} else if ("分类".equals(title)) {
			for (int i = 0; i < Const.types.size() - 1; i++) {
				items3[i] = Const.types.get(i);
			}
			items = items3;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setSingleChoiceItems(items, selected,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {

						if ("距离".equals(title)) {
							if (item != rigionItem) {
								rigionItem = item;
								rigion.setText(items1[item]);
								shopList.clear();
								adapter.notifyDataSetChanged();
								listView.addFooterView(footer);
								num.setText(getString(R.string.business_num, 0));
								if (item == 0) {
									location.setRadius(500);
								} else if (item == 1) {
									location.setRadius(1000);
								} else if (item == 1) {
									location.setRadius(2000);
								}
								new BusinessListTask(listType)
										.execute(location);
							}
						} else if ("分类".equals(title)) {
							if (item != typeItem) {
								typeItem = item;
								type.setText(items3[item]);
								shopList.clear();
								adapter.notifyDataSetChanged();
								listView.addFooterView(footer);
								num.setText(getString(R.string.business_num, 0));
								if (item == 0) {
									location.setCategory(Const.MEISHI);
									BusinessList.this.title.setText("附近-美食");
								} else if (item == 1) {
									location.setCategory(Const.LIREN);
									BusinessList.this.title.setText("附近-丽人");
								} else if (item == 2) {
									location.setCategory(Const.HUAJIA);
									BusinessList.this.title.setText("附近-花嫁");
								} else if (item == 3) {
									location.setCategory(Const.QINZI);
									BusinessList.this.title.setText("附近-亲子");
								} else if (item == 4) {
									location.setCategory(Const.JIANSHEN);
									BusinessList.this.title.setText("附近-健身");
								} else if (item == 5) {
									location.setCategory(Const.PEIXUN);
									BusinessList.this.title.setText("附近-培训");
								} else if (item == 6) {
									location.setCategory(Const.YOUXIANYULE);
									BusinessList.this.title.setText("附近-休闲娱乐");
								} else if (item == 7) {
									location.setCategory(Const.GOUWU);
									BusinessList.this.title.setText("附近-购物");
								} else if (item == 8) {
									location.setCategory(Const.JIUDIAN);
									BusinessList.this.title.setText("附近-酒店");
								} else if (item == 9) {
									location.setCategory(Const.SHENGHUOFUWU);
									BusinessList.this.title.setText("附近-生活服务");
								}
								// new BusinessListTask(listType)
								// .execute(location);
							}

						} else if ("排序".equals(title)) {

							if (item != concernItem) {
								concernItem = item;
								concern.setText(items2[item]);
								shopList.clear();
								adapter.notifyDataSetChanged();
								listView.addFooterView(footer);
								num.setText(getString(R.string.business_num, 0));
								if (item == 0) {
									location.setOrderBy("distance");
								} else if (item == 1) {
									location.setOrderBy("rating");
								} else if (item == 2) {
									location.setOrderBy("concern_num");
								} else if (item == 3) {
									location.setOrderBy("is_coupon");
								} else if (item == 4) {
									location.setOrderBy("info_num");
								}
								new BusinessListTask(listType)
										.execute(location);
							}

						}
						dialog.dismiss();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private class BitmapTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			long id = System.currentTimeMillis();
			taskId = id;
			// 增加一个缓存List避免列表长度变化时遍历发生错误
			List<Shop> cacheList = new ArrayList<Shop>();
			cacheList.addAll(shopList);
			Iterator<Shop> it = cacheList.iterator();
			while (it.hasNext()) {
				/*
				 * 避免重复下载,如果有新的线程,则停止老的线程
				 */
				if (id != taskId) {
					break;
				}
				Shop shop = it.next();
				Bitmap icon = null;
				try {
					if (shop.getIcon() == mooerApp.getShopListDefaultIcon()) {
						icon = HttpUtils.downloadBitmap(
								String.valueOf(shop.getId()), shop.getLogo());
						shop.setIcon(icon);
						publishProgress(0);
					}
				} catch (Exception e) {

				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			adapter.notifyDataSetChanged();
		}

	}

}
